package com.zhang.genericdemo.case1.client;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zhang.genericdemo.case1.request.GoodsDetailRequest;
import com.zhang.genericdemo.case1.request.GoodsListRequest;
import com.zhang.genericdemo.case1.response.GoodsDetailResponse;
import com.zhang.genericdemo.case1.response.GoodsListResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @Author: ZhangGongMing
 * @CreateTime: 2025/5/16 23:38
 * @Description:
 * @Version: 1.0
 */
@Service
@AllArgsConstructor
public class Client {

    /**
     * 此处这个方法的作用是外部系统开放给我们的请求接口.通过传参到这个接口拿到返回回来的响应
     * <p>
     * TODO 需要注意的是: 通过 URL 调用到外部系统时,由于涉及到网络传输,需要将返回结果序列化为 JSON 字符串返回调用方
     *
     * @param body
     * @return
     */
    private String postRequest(String body) {
        return HttpUtil.createPost("http://localhost:8080/api").body(body).execute().body();
    }


    /**
     * 获取商品列表
     *
     * @param request
     * @return
     */
    public GoodsListResponse getGoodsList(GoodsListRequest request) {
        String result = postRequest(JSONUtil.toJsonStr(request));
        return JSONUtil.toBean(result, GoodsListResponse.class);
    }

    /**
     * 获取商品详情
     *
     * @param request
     * @return
     */
    public GoodsDetailResponse getGoodsDetail(GoodsDetailRequest request) {
        String result = postRequest(JSONUtil.toJsonStr(request));
        return JSONUtil.toBean(result, GoodsDetailResponse.class);
    }
}
